package com.study.pdf;
import com.lowagie.text.pdf.BaseFont;
import freemarker.template.TemplateException;
import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.xhtmlrenderer.pdf.ITextRenderer;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.*;
import java.util.Map;
/**
 * <p>添加类描述</p>
 *
 * @author chentao
 * @version v 0.1 2021/10/14 15:10
 */
public class PdfDocumentGenerator {

    private final static HtmlGenerator htmlGenerator;
    static {
        htmlGenerator = new HtmlGenerator();
    }


    /*
     *
     * 根据html的内容生成pdf
     *
     */
    public static byte[] pdfgenerate(String htmlContent)throws Exception{

        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = builder.parse(new ByteArrayInputStream(htmlContent.getBytes("UTF-8")));
        ITextRenderer iTextRenderer = new ITextRenderer();
        //添加字体，以支持中文
       // iTextRenderer.getFontResolver().addFont(Constants.templatePath + "/fonts/simsun.ttc", BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
        iTextRenderer.getFontResolver().addFont("D:\\test\\" + "arialuni.ttf", BaseFont.IDENTITY_H,
                BaseFont.NOT_EMBEDDED);
        iTextRenderer.getFontResolver().addFont("D:\\test\\" + "simsun.ttc", BaseFont.IDENTITY_H,
                BaseFont.NOT_EMBEDDED);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        iTextRenderer.setDocument(doc, null);
        iTextRenderer.layout();
        iTextRenderer.createPDF(out);
        byte[] bytes = out.toByteArray();
        out.close();
        return bytes;
    }
}
